#include "keyboard_event_panel.hpp"
#include <iostream>
#include <QPainter>
#include <QFont>
#include <QKeyEvent>

KeyBoardEventPanel::KeyBoardEventPanel()
{
  std::cout << "create KeyBoardEventPanel instance..." << std::endl;
  this->setFixedSize(800, 600);
  grabKeyboard();
}

void KeyBoardEventPanel::paintEvent(QPaintEvent *event)
{
  QPainter painter(this);
  painter.setRenderHint(QPainter::Antialiasing, true);
  painter.setPen(QColor(0, 255, 0));
  painter.fillRect(this->rect(), QColor(0, 0, 0));

  QFont font;
  font.setBold(true);
  font.setPixelSize(36);
  painter.setFont(font);
  painter.drawText(QPoint(100, 100), this->textInfo);

  // 绘制跟填充不同的几何形状
  QBrush brush(Qt::blue);
  painter.setBrush(brush);
  QPen pen(Qt::green);
  pen.setWidth(4);
  pen.setStyle(Qt::SolidLine);
  painter.setPen(pen);
  painter.drawEllipse(QPoint(this->cx, this->cy), this->radius, this->radius);
}

void KeyBoardEventPanel::keyPressEvent(QKeyEvent *event)
{
  // std::cout << "KeyBoardEventPanel::keyPressEvent..." << std::endl;
  std::cout << "x: " << this->cx << " y: " << this->cy << std::endl;
}

void KeyBoardEventPanel::keyReleaseEvent(QKeyEvent *event)
{
  if (event->key() == Qt::Key_Left)
  {
    if (this->cx - radius > 0) this->cx -= 2;
  }
  if (event->key() == Qt::Key_Right)
  {
    if (this->cx + radius < this->width()) this->cx += 2;
  }
  if (event->key() == Qt::Key_Up)
  {
    if (this->cy - radius > 0) this->cy -= 2;
  }
  if (event->key() == Qt::Key_Down)
  {
    if (this->cy + radius < this->height()) this->cy += 2;
  }

  if (this->cx - radius >= 0 && this->cy - radius >= 0 && this->cx + radius <= this->width() && this->cy + radius <= this->height())
  {
    this->repaint();
  }
}
